<template>
  <div class="app-container" v-loading="pageLoading">
    <el-button key="import" class="fr" type="success" style="margin-right: 5px;" @click="dialogExcelVisible = true"
      v-permission="'adminUser.add'">导入
    </el-button>
    <el-button type="primary" class="fr mr-5" @click="createItem" v-permission="'adminUser.add'">创建</el-button>
    <div class="filter-container">
      <el-input style="width: 180px;" placeholder="输入查询条件按回车" clearable prefix-icon="el-icon-search" class="filter-item"
        @keyup.enter.native="research" @clear="research" v-model="query.queryString"></el-input>
      <!-- <el-select class="filter-item" style="width: 140px;" v-model="query.deptid" placeholder="选择部门" filterable remote
        clearable :remote-method="getSelectOrgOptions" @change="research">
        <el-option v-for="(item,index) in orgOptions" :key="index" :value="item.value" :label="item.label"></el-option>
      </el-select> -->
      <el-cascader class="filter-item" v-model="query.deptid" :options="orgOptions" :props="{ checkStrictly: true }"
        :show-all-levels="false" clearable>
      </el-cascader>
      <el-select class="filter-item" style="width: 140px;" v-model="query.status" placeholder="选择状态" filterable
        clearable @change="research">
        <el-option v-for="(item,index) in userStatus" :key="index" :value="item.value" :label="item.label"></el-option>
      </el-select>
      <el-button class="filter-item" type="success" plain @click="research">查询</el-button>
      <el-button class="filter-item" type="info" plain @click="exportData" :loading="exportLoading">导出
      </el-button>
    </div>
    <z-table :list="list" :tableProps="tableProps" :columns="columns" @editItem="editItem" @deleteItem="deleteItem">
      <template v-slot:content="{ row, key }">
        <div v-if="key == 'enabled'">
          <span class="text-label" :class="row[key] ? 'bg-green' : 'bg-gray'">
            {{row[key]?'已启用':'已禁用'}}
          </span>
        </div>
        <span v-else>{{ row[key] }}</span>
      </template>
      <template v-slot:operation="v">
        <a href="#" class="text-blue" @click.prevent="editItem(v.row,v.$index)" v-permission="'adminUser.edit'">编辑</a>
        <span>&nbsp;</span>
        <a href="#" class="text-yellow" @click.prevent="resetPass(v.row,v.$index)"
          v-permission="'adminUser.edit'">重置密码</a>
        <span>&nbsp;</span>
        <a href="#" class="text-red" @click.prevent="deleteItem(v.row,v.$index)"
          v-permission="'adminUser.delete'">删除</a>
      </template>
    </z-table>
    <z-pagination :pagination="pagination" :total="total" :page.sync="query.page" :limit.sync="query.size"
      @change="getList"></z-pagination>
    <z-form-dialog :name="name" :data="data" :formProps="formProps" :fields="fields" @submit="submit"
      :submitLoading="submitLoading" :visible.sync="editFormVisible"></z-form-dialog>
    <el-dialog title="Excel导入" :visible.sync="dialogExcelVisible">
      <div style="margin-bottom: 10px;"><a href="#" @click.prevent="getTemp1">下载批量导入用户模板</a></div>
      <div style="margin-bottom: 10px;"><a href="#" @click.prevent="getTemp2">下载批量禁用/启用用户模板</a></div>
      <upload-excel-component ref="uploadExcel" :on-success="handleSuccess" :before-upload="beforeUpload" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogExcelVisible = false">取消</el-button>
        <el-button type="primary" :loading="excelLoading" @click="excelSubmit()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import commonMixin from '@/views/_common/mixin'
import UploadExcelComponent from '@/components/UploadExcel'
import dayjs from 'dayjs'
import { generateCascaderOption } from '@/utils'

export default {
  name: 'adminUser',
  mixins: [commonMixin],
  components: { UploadExcelComponent },
  data: function () {
    return {
      name: '用户',
      api: this.$api.user,
      columns: [
        { title: '账号', key: 'userid' },
        { title: '姓名', key: 'username' },
        { title: '部门', key: 'dept_name' },
        { title: '邮箱', key: 'email' },
        { title: '手机号', key: 'telephone' },
        { title: '启用状态', key: 'enabled' },
        { title: '修改时间', key: 'modify_time' },
      ],
      fields: [
        { title: '账号', key: 'userid', required: true },
        { title: '姓名', key: 'username', required: true },
        // { title: '部门', key: 'department', required: true },
        {
          title: '部门',
          key: 'dept_id',
          required: true,
          name: 'cascader',
          options: [],
          props: {
            clearable: true,
            showAllLevels: false,
            props: {
              checkStrictly: true,
              emitPath: false,
            },
          },
        },
        { title: '邮箱', key: 'email' },
        { title: '手机号', key: 'telephone' },
        {
          title: '角色',
          key: 'roles',
          name: 'select',
          props: {
            options: [],
            filterable: true,
            multiple: true,
            clearable: true,
          },
        },
        {
          title: '启用状态',
          key: 'enabled',
          name: 'switch',
          props: {
            activeValue: true,
            inactiveValue: false,
          },
        },
      ],
      tableProps: {
        border: true,
        opsColWith: 140,
      },
      query: {
        queryString: null,
        size: 10,
        page: 1,
        status: 1,
        deptid: [],
      },
      initData: {
        enabled: true,
        roles: [],
      },
      dialogExcelVisible: false,
      excelLoading: false,
      excelData: [],
      userStatus: [
        { label: '已启用', value: 1 },
        { label: '已禁用', value: 0 },
      ],
      orgOptions: [],
      syncLoading: false,
    }
  },
  methods: {
    // 获取组织
    getOrgOptions(v) {
      this.setFieldOptions('dept_id', [], 'id', ['dept_code', 'dept_name'])
      this.$request(this.$api.organize + 'getList?size=200' + '&queryString=' + v).then((r) => {
        this.setFieldOptions('dept_id', r.list, 'id', ['dept_code', 'dept_name'])
        console.log(this.getFieldConfig('dept_id'))
      })
    },
    // 筛选项获取组织
    getSelectOrgOptions(v) {
      this.orgOptions = []
      // this.$request(this.$api.organize + 'getList?size=200' + '&queryString=' + v).then((r) => {
      //   // this.orgOptions = this.formatSelectOption(r.list)
      //   this.orgOptions = generateCascaderOption('parent_id', 0, 'id', r.list, ['dept_code', 'dept_name'])
      // })
      this.$request(this.$api.organize + 'getAllList').then((r) => {
        this.orgOptions = this.formatSelectOption(r)
        var conf = this.getFieldConfig('dept_id')
        conf.options = this.orgOptions
      })
    },
    formatSelectOption(data) {
      if (data && data.length > 0) {
        for (let i = 0; i < data.length; i++) {
          data[i].label = data[i].dept_code + ' ' + data[i].dept_name
          data[i].value = data[i].id
          if (data[i].children.length == 0) {
            delete data[i].children
          } else {
            data[i].children = this.formatSelectOption(data[i].children)
          }
        }
      }
      return data
    },
    formatQuery(query) {
      let tmp = _.cloneDeep(query)
      if (tmp.deptid.length) {
        tmp.deptid = query.deptid[query.deptid.length - 1]
      }
      return tmp
    },
    createItem() {
      this.data = _.cloneDeep(this.initData)
      if (this.query.deptid) this.data.dept_id = this.query.deptid
      this.editFormVisible = true
    },
    editItem(row) {
      this.data = { roles: [], enabled: true }
      this.pageLoading = true
      this.$request(this.api + 'getWithRoles', { userid: row.userid })
        .then((r) => {
          this.data = r
          this.editFormVisible = true
          this.pageLoading = false
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    formatBeforeSave(data) {
      //依据实际需求处理
      let tmp = _.cloneDeep(data)
      tmp.userroles = tmp.roles.join('/')
      delete tmp.roles
      return tmp
    },
    deleteItem(v) {
      this.$confirm('确定要删除这条记录？', '操作确认').then(() => {
        this.pageLoading = true
        this.$request(this.api + 'delete/' + v.userid, {}, 'post')
          .then((r) => {
            this.pageLoading = false
            this.$message({
              message: '操作成功',
              type: 'success',
            })
            this.getList()
          })
          .catch(() => {
            this.pageLoading = false
          })
      })
    },
    resetPass(v) {
      this.$confirm('将要把 ' + v.userid + ' 的密码重置为与其用户名一致，是否确认？', '操作确认').then(() => {
        this.pageLoading = true
        this.$request(this.api + 'resetpassword', { user: v.userid }, 'post')
          .then((r) => {
            this.pageLoading = false
            this.$message({
              message: '操作成功',
              type: 'success',
            })
          })
          .catch(() => {
            this.pageLoading = false
          })
      })
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 20
      if (!isLt1M) {
        this.$message({
          message: '文件大小必须小于20M',
          type: 'warning',
        })
        return false
      }
      return true
    },
    handleSuccess({ results, header }) {
      this.excelData = []
      results.forEach((v) => {
        let tmp = []
        header.forEach((i) => {
          tmp.push(v[i])
        })
        this.excelData.push(tmp)
      })
    },
    excelSubmit() {
      if (this.excelData.length <= 0) {
        this.$message({
          message: '请先选择Excel文件',
          type: 'error',
        })
        return false
      }
      var url = this.api + 'addbatch'
      if (this.excelData[0].length == 2) {
        url = this.api + 'batchEnableOrDisable'
      }
      this.excelLoading = true
      this.$request(url, this.excelData, 'post')
        .then((r) => {
          this.excelLoading = false
          this.getList()
          this.$message({
            message: 'Excel导入成功',
            type: 'success',
          })
          this.excelData = []
          this.$refs.uploadExcel.clear()
          this.dialogExcelVisible = false
        })
        .catch((e) => {
          this.excelLoading = false
        })
    },
    getTemp1() {
      import('@/vendor/Export2Excel')
        .then((excel) => {
          excel.export_json_to_excel({
            header: ['用户账户', '姓名', '部门编号', '电话', '邮箱'],
            data: [['lisi', '李四', 'test', '13000000000', '123456@xx.com']],
            filename: this.name + '导入_' + dayjs().format('YYYYMMDD'),
          })
        })
        .catch(() => {})
    },
    getTemp2() {
      import('@/vendor/Export2Excel')
        .then((excel) => {
          excel.export_json_to_excel({
            header: ['用户账户', '是否启用Y/N'],
            data: [['lisi', 'Y']],
            filename: this.name + '禁用启用_' + dayjs().format('YYYYMMDD'),
          })
        })
        .catch(() => {})
    },
    syncData() {
      this.syncLoading = true
      this.$request(this.$api.oeeSyncData + 'syncuser', {}, 'post')
        .then((r) => {
          this.$message.success('操作成功')
          this.getList()
        })
        .finally((_) => {
          this.syncLoading = false
        })
    },
  },
  created: function () {
    this.getList()
    this.$request(this.$api.role + 'getlist', { size: 9999 })
      .then((r) => {
        this.setFieldOptions('roles', r.list, 'id', ['role_code', 'role_name'])
      })
      .catch(() => {})
    this.getSelectOrgOptions('')
  },
  watch: {
    data: function (nv, ol) {
      if (nv.Id) {
        this.setFieldsDisable(true, 'userid')
      } else {
        this.setFieldsDisable(false, 'userid')
      }
    },
  },
}
</script>
<style scoped>
</style>
